﻿#region License
/*
Copyright (c) 2005-2011, CellAO Team

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the CellAO Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion

#region Usings...
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Collections;
using AO.Core;
using Cell.Core;
using ZoneEngine.Database;
using ZoneEngine.Misc;
#endregion

namespace ZoneEngine.Packets
{
    /// <summary>
    /// 
    /// </summary>
    public static class SimpleCharFullUpdate
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="client"></param>
        public static void SendToPf(Client client)
        {
            byte[] mReply = GetPacket(client);
            Misc.Announce.Playfield(client.Character.PlayField, ref mReply);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="client"></param>
        public static void SendToPfOthers(Client client)
        {
            Byte[] data = GetPacket(client);
            Misc.Announce.PlayfieldOthers(client, ref data);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="client"></param>
        /// <param name="receiver"></param>
        public static void SendToOne(Client client, Client receiver)
        {
            Byte[] data = WritePacket(client, receiver.Character.ID);
            receiver.SendCompressed(data);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        public static Byte[] GetPacket(Client client)
        {
            return WritePacket(client, client.Character.ID);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="client"></param>
        /// <param name="receiver"></param>
        /// <returns></returns>
        public static Byte[] WritePacket(Client client, int receiver)
        {
            /*
             * To set a packetFlag use       packetFlags |= <flagHere>;
             * To unset a packetFlag use     packetFlags &= ~<flagHere>;
             * 
             * Wherever you set a flag conditionally, be sure to unset the same flag if the reverse
             * condition is true 'just in case'.
             */
            int packetFlags = 0; // Try setting to 0x042062C8 if you have problems (old value)

            //
            // Character Variables

            bool socialonly;
            bool showsocial;
            bool showhelmet;
            bool LeftPadVisible;
            bool RightPadVisible;
            bool DoubleLeftPad;
            bool DoubleRightPad;

            int CharPlayfield;
            AOCoord CharCoord;
            int CharID;
            Quaternion CharHeading;

            uint SideValue;
            uint FatValue;
            uint BreedValue;
            uint SexValue;
            uint RaceValue;

            int NameLength;
            string CharName;
            int CharFlagsValue;
            int AccFlagsValue;

            int ExpansionValue;
            int CurrentNano;

            uint StrengthBaseValue;
            uint StaminaBaseValue;
            uint AgilityBaseValue;
            uint SenseBaseValue;
            uint IntelligenceBaseValue;
            uint PsychicBaseValue;

            int FirstNameLength;
            int LastNameLength;
            string FirstName;
            string LastName;
            int OrgNameLength;
            string OrgName;
            int LevelValue;
            int HealthValue;

            int MonsterData;
            int MonsterScale;
            int VisualFlags;

            int CurrentMovementMode;
            uint RunSpeedBaseValue;

            int TexturesCount;
            int HairMeshValue;
            int WeaponMeshRightValue;
            int WeaponMeshLeftValue;

            uint HeadMeshBaseValue;
            int HeadMeshValue;

            int BackMeshValue;
            int ShoulderMeshRightValue;
            //int ShoulderMeshLeftValue;

            int OverrideTextureHead;
            int OverrideTextureWeaponRight;
            int OverrideTextureWeaponLeft;
            int OverrideTextureShoulderpadRight;
            int OverrideTextureShoulderpadLeft;
            int OverrideTextureBack;
            int OverrideTextureAttractor;

            Dictionary<int, int> SocialTab = new Dictionary<int, int>();

            List<AOTextures> Textures = new List<AOTextures>();

            List<AOMeshs> mh = new List<AOMeshs>();

            lock (client)
            {
                socialonly = ((client.Character.Stats.VisualFlags.Value & 0x40) > 0);
                showsocial = ((client.Character.Stats.VisualFlags.Value & 0x20) > 0);
                showhelmet = ((client.Character.Stats.VisualFlags.Value & 0x4) > 0);
                LeftPadVisible = ((client.Character.Stats.VisualFlags.Value & 0x1) > 0);
                RightPadVisible = ((client.Character.Stats.VisualFlags.Value & 0x2) > 0);
                DoubleLeftPad = ((client.Character.Stats.VisualFlags.Value & 0x8) > 0);
                DoubleRightPad = ((client.Character.Stats.VisualFlags.Value & 0x10) > 0);

                CharPlayfield = client.Character.PlayField;
                CharCoord = client.Character.Coordinates;
                CharID = client.Character.ID;
                CharHeading = client.Character.Heading;

                SideValue = client.Character.Stats.Side.StatBaseValue;
                FatValue = client.Character.Stats.Fatness.StatBaseValue;
                BreedValue = client.Character.Stats.Breed.StatBaseValue;
                SexValue = client.Character.Stats.Sex.StatBaseValue;
                RaceValue = client.Character.Stats.Race.StatBaseValue;

                NameLength = client.Character.Name.Length;
                CharName = client.Character.Name;
                CharFlagsValue = client.Character.Stats.Flags.Value;
                AccFlagsValue = client.Character.Stats.AccountFlags.Value;

                ExpansionValue = client.Character.Stats.Expansion.Value;
                CurrentNano = client.Character.Stats.CurrentNano.Value;

                StrengthBaseValue = client.Character.Stats.Strength.StatBaseValue;
                StaminaBaseValue = client.Character.Stats.Strength.StatBaseValue;
                AgilityBaseValue = client.Character.Stats.Strength.StatBaseValue;
                SenseBaseValue = client.Character.Stats.Strength.StatBaseValue;
                IntelligenceBaseValue = client.Character.Stats.Strength.StatBaseValue;
                PsychicBaseValue = client.Character.Stats.Strength.StatBaseValue;

                FirstNameLength = client.Character.FirstName.Length;
                LastNameLength = client.Character.LastName.Length;
                FirstName = client.Character.FirstName;
                LastName = client.Character.LastName;
                OrgNameLength = client.Character.orgName.Length;
                OrgName = client.Character.orgName;
                LevelValue = client.Character.Stats.Level.Value;
                HealthValue = client.Character.Stats.Health.Value;

                MonsterData = client.Character.Stats.MonsterData.Value;
                MonsterScale = client.Character.Stats.MonsterScale.Value;
                VisualFlags = client.Character.Stats.VisualFlags.Value;

                CurrentMovementMode = client.Character.Stats.CurrentMovementMode.Value;
                RunSpeedBaseValue = client.Character.Stats.RunSpeed.StatBaseValue;

                TexturesCount = client.Character.Textures.Count;
                HairMeshValue = client.Character.Stats.HairMesh.Value;
                WeaponMeshRightValue = client.Character.Stats.WeaponMeshRight.Value;
                WeaponMeshLeftValue = client.Character.Stats.WeaponMeshLeft.Value;

                HeadMeshBaseValue = client.Character.Stats.HeadMesh.StatBaseValue;
                HeadMeshValue = client.Character.Stats.HeadMesh.Value;

                BackMeshValue = client.Character.Stats.BackMesh.Value;
                ShoulderMeshRightValue = client.Character.Stats.ShoulderMeshRight.Value;
                //ShoulderMeshLeftValue = client.Character.Stats.ShoulderMeshLeft.Value;

                OverrideTextureHead = client.Character.Stats.OverrideTextureHead.Value;
                OverrideTextureWeaponRight = client.Character.Stats.OverrideTextureWeaponRight.Value;
                OverrideTextureWeaponLeft = client.Character.Stats.OverrideTextureWeaponLeft.Value;
                OverrideTextureShoulderpadRight = client.Character.Stats.OverrideTextureShoulderpadRight.Value;
                OverrideTextureShoulderpadLeft = client.Character.Stats.OverrideTextureShoulderpadLeft.Value;
                OverrideTextureBack = client.Character.Stats.OverrideTextureBack.Value;
                OverrideTextureAttractor = client.Character.Stats.OverrideTextureAttractor.Value;

                foreach (int num in client.Character.SocialTab.Keys)
                {
                    SocialTab.Add(num, client.Character.SocialTab[num]);
                }

                foreach (AOTextures at in client.Character.Textures)
                {
                    Textures.Add(new AOTextures(at.place, at.Texture));
                }

                mh = Misc.MeshLayers.GetMeshs(client.Character, showsocial, socialonly);
            }
            PacketWriter _writer = new PacketWriter();

            // Packet Header
            _writer.PushByte(0xDF);
            _writer.PushByte(0xDF);
            _writer.PushShort(10);
            _writer.PushShort(1);
            _writer.PushShort(0);           // length. writer will take care of this
            _writer.PushInt(3086);          // sender. our server ID
            _writer.PushInt(receiver);      // receiver
            _writer.PushInt(0x271B3A6B);    // packet ID
            _writer.PushIdentity(50000, CharID); // affected identity
            _writer.PushByte(0);            // Unknown?
            // End Packet Header

            _writer.PushByte(57);   // SCFU packet version (57/0x39)
            _writer.PushInt(0);     // packet flags (this is set later based on packetFlags variable above)

            packetFlags |= 0x40;    // Has Playfield ID
            _writer.PushInt(CharPlayfield);   // playfield

            //if (packetFlags & 0x20)
            //{
            //    // Pop2Long
            //    /*
            //     * Is this a Type:Instance pair?
            //     * Suspect so as it uses Pop2Long
            //     * which is used for Type:Instance
            //     * pairs. Perhaps pet master?
            //     * (Just a wild guess though that its pet master)
            //     */
            //    long unknown;
            //    long unknown;
            //}

            // Coordinates
            _writer.PushCoord(CharCoord);

            // Heading Data
            packetFlags |= 0x200; // Has Heading Data Flag
            _writer.PushQuat(CharHeading);

            uint m_appearance = SideValue + (FatValue * 8) + (BreedValue * 32) + (SexValue * 256) + (RaceValue * 1024); // Race
            _writer.PushUInt(m_appearance);  // appearance

            // Name
            _writer.PushByte((byte)(NameLength + 1));
            _writer.PushBytes(Encoding.ASCII.GetBytes(CharName));
            _writer.PushByte(0);    // 0 terminator for name

            _writer.PushUInt(CharFlagsValue); // Flags
            _writer.PushShort((short)AccFlagsValue);
            _writer.PushShort((short)ExpansionValue);

            packetFlags &= ~0x01; // We are a player
            if ((packetFlags & 0x01) != 0)
            {
                // Are we a NPC (i think anyway)? So far this is _NOT_ used at all

                //if (packetFlags & 0x20000)
                //{
                //    char NPCFamily;
                //}
                //else
                //{
                //    short NPCFamily;
                //}

                //if (packetFlags & 0x80000)
                //{
                //    char LOSHeight?;
                //}
                //else
                //{
                //    short LOSHeight?;
                //}

                //if (packetFlags & 0x2000000)
                //{
                //    char PetType;
                //}
                //else
                //{
                //    short PetType;
                //}

                //short TowerType;

                //if (TowerType > 0)
                //{
                //    char unknown;
                //}
            }
            else
            {
                // Are we a player?
                _writer.PushUInt(CurrentNano); // CurrentNano
                _writer.PushInt(0); // team?
                _writer.PushShort(5);   // swim?

                // The checks here are to prevent the client doing weird things if the character has really large or small base attributes
                if (StrengthBaseValue > 32767) // Strength
                {
                    _writer.PushShort((short)32767);
                }
                else
                {
                    _writer.PushShort((short)StrengthBaseValue);
                }
                if (AgilityBaseValue > 32767) // Agility
                {
                    _writer.PushShort((short)32767);
                }
                else
                {
                    _writer.PushShort((short)AgilityBaseValue);
                }
                if (StaminaBaseValue > 32767) //  Stamina
                {
                    _writer.PushShort((short)32767);
                }
                else
                {
                    _writer.PushShort((short)StaminaBaseValue);
                }
                if (IntelligenceBaseValue > 32767) // Intelligence
                {
                    _writer.PushShort((short)32767);
                }
                else
                {
                    _writer.PushShort((short)IntelligenceBaseValue);
                }
                if (SenseBaseValue > 32767) // Sense
                {
                    _writer.PushShort((short)32767);
                }
                else
                {
                    _writer.PushShort((short)SenseBaseValue);
                }
                if (PsychicBaseValue > 32767) // Psychic
                {
                    _writer.PushShort((short)32767);
                }
                else
                {
                    _writer.PushShort((short)PsychicBaseValue);
                }

                if ((CharFlagsValue & 0x400000) != 0)  // has visible names? (Flags)
                {
                    _writer.PushShort((short)FirstNameLength);
                    _writer.PushBytes(Encoding.ASCII.GetBytes(FirstName));
                    _writer.PushShort((short)LastNameLength);
                    _writer.PushBytes(Encoding.ASCII.GetBytes(LastName));
                }

                if (OrgNameLength != 0)
                {
                    packetFlags |= 0x4000000; // Has org name data

                    _writer.PushShort((short)OrgNameLength);
                    _writer.PushBytes(Encoding.ASCII.GetBytes(OrgName));
                }
                else
                {
                    packetFlags &= ~0x4000000; // Does not have org name data
                }
            }

            if (LevelValue > 127) // Level
            {
                packetFlags |= 0x1000; // Has Extended Level
                _writer.PushShort((short)LevelValue);
            }
            else
            {
                packetFlags &= ~0x1000; // Has Small Level
                _writer.PushByte((byte)LevelValue);
            }

            if (HealthValue > 32767) // Health
            {
                packetFlags &= ~0x800; // Has Extended Health
                _writer.PushUInt(HealthValue);
            }
            else
            {
                packetFlags |= 0x800; // Has Small Health
                _writer.PushShort((short)HealthValue);
            }

            packetFlags |= 0x4000; // If this is not set, then we have a short or long based on flag 0x800 (Health size)
            if ((packetFlags & 0x4000) != 0)
            {
                _writer.PushByte(0);    // ?
            }
            else
            {
                //if (packetFlags & 0x800)
                //{
                //    short unknown;
                //}
                //else
                //{
                //    long unknown;
                //}
            }
            // If player is in grid or fixer grid
            // make him/her/it a nice upside down pyramid
            if ((CharPlayfield == 152) || (CharPlayfield == 4107))
            {
                _writer.PushInt(99902);
            }
            else
            {
                _writer.PushUInt(MonsterData); // Monsterdata
            }
            _writer.PushShort((short)MonsterScale); // Monsterscale
            _writer.PushShort((short)VisualFlags); // VisualFlags
            _writer.PushByte(0);    // visible title?

            _writer.PushInt(42);    // 'skipdata' length
            // Start 'skipdata'
            _writer.PushBytes(new Byte[]
            {
                0x80, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00,
                0x80, 0x00, 0x00, 0x00
            });
            _writer.PushByte((byte)CurrentMovementMode); // CurrentMovementMode
            _writer.PushByte(1);    // don't change
            _writer.PushShort(1);   // ?
            _writer.PushShort(1);   // ?
            _writer.PushShort(1);   // ?
            _writer.PushShort(1);   // ?
            _writer.PushShort(0);   // ?
            _writer.PushShort(3);   // ?
            _writer.PushInt(0); //?
            _writer.PushInt(0); //?
            _writer.PushInt(0); //?
            _writer.PushInt(0); //?
            // End 'skipdata'

            packetFlags |= 0x80; // Has HeadMesh Flag
            _writer.PushUInt(HeadMeshValue); // Headmesh

            if ((RunSpeedBaseValue > 127)) // Runspeed
            {
                packetFlags |= 0x2000;
                _writer.PushShort((short)RunSpeedBaseValue);
            }
            else
            {
                packetFlags &= ~0x2000;
                _writer.PushByte((byte)RunSpeedBaseValue);
            }

            //if (packetFlags & 0x400)
            //{
            //    // Pop2Long
            //    /*
            //     * Is this a Type:Instance pair?
            //     * Suspect so as it uses Pop2Long
            //     * which is used for Type:Instance
            //     * pairs. Perhaps pet master?
            //     * (Just a wild guess though that its pet master)
            //     */
            //    long unknown;
            //    long unknown;
            //}

            //if (packetFlags & 0x10)
            //{
            //    long counter;
            //    repeat (counter / 0x3F1 - 1) times
            //        char texturepositionname[32]; // Null padded at the end
            //        long textureid; // Or is this mesh id? (Damn you suiv :P)
            //        long unknown;
            //        long unknown;
            //    end repeat
            //}

            // Is char/NPC in hide mode?
            //if (packetFlags & 0x100000)
            //{
            //    short Concealment;
            //}

            //if (packetFlags & 0x800000)
            //{
            //    char unknown;
            //}

            //if (packetFlags & 0x1000000)
            //{
            //    char unknown;
            //}

            _writer.Push3F1Count(0);    // running nanos count
            // longx5: aoid, instance, unknown(0?), timer1, timer2

            //if (flags & 0x10000)
            //{
            //    // Waypoint Info
            //    // Pop2Long (1010E2D3)
            //    long type;
            //    long instance;
            //    // Waypoint Counter - 3x float per entry
            //    long counter;
            //    repeat counter times
            //        float x;
            //        float y;
            //        float z;
            //    end repeat
            //    // End Waypoint Counter
            //}

            // Texture/Cloth Data
            int c;
            int c2;
            Textures tx = new Textures();
            tx.GetTextures(CharID);
            _writer.Push3F1Count(5);    // textures count

            AOTextures aotemp = new AOTextures(0, 0);
            for (c = 0; c < 5; c++)
            {
                aotemp.Texture = 0;
                aotemp.place = c;
                for (c2 = 0; c2 < TexturesCount; c2++)
                {
                    if (Textures[c2].place == c)
                    {
                        aotemp.Texture = Textures[c2].Texture;
                        break;
                    }
                }
                if (showsocial)
                {
                    if (socialonly)
                    {
                        aotemp.Texture = SocialTab[c];
                    }
                    else
                    {
                        if (SocialTab[c] != 0)
                        {
                            aotemp.Texture = SocialTab[c];
                        }
                    }
                }

                _writer.PushInt(aotemp.place);
                _writer.PushInt(aotemp.Texture);
                _writer.PushInt(0);
            }
            // End Textures

            // ############
            // # Meshs
            // ############

            c = mh.Count;

            _writer.Push3F1Count(c);
            foreach (AOMeshs m2 in mh)
            {
                _writer.PushByte((byte)m2.Position);
                _writer.PushUInt(m2.Mesh);
                _writer.PushInt(m2.OverrideTexture);  // Override Texture!!!!!!
                _writer.PushByte((byte)m2.Layer);
            }
            // End Meshs

            //if (packetFlags & 0x100)
            //{
            //    // 0x3F1 Unknown Counter - 4x long per entry
            //    long counter;
            //    repeat (counter / 0x3F1 - 1) times
            //        long unknown;
            //        long unknown;
            //        long unknown;
            //        long unknown;
            //    end repeat
            //}

            //if (packetFlags & 0x20000000)
            //{
            //    char ShadowBreed;
            //}

            //if (packetFlags & 0x40000000)
            //{
            //    // 0x3F1 Unknown Counter - 4x long per entry
            //    long counter;
            //    repeat (counter / 0x3F1 - 1) times
            //        Pop2Long (Type:Instance pair maybe?)
            //        long unknown;
            //        long unknown;
            //    end repeat
            //}

            _writer.PushInt(0); // packetFlags2

            // Some mech stuff
            //if (packetFlags2 & 0x01)
            //{
            //    long counter;
            //    repeat (counter) times
            //        long unknown;
            //        long unknown;
            //    end repeat

            //    long MechData;
            //    // Pop2Long (Type:Instance pair maybe?)
            //    long unknown;
            //    long unknown;
            //}

            // maybe check if we are in battlestation
            //if (packetFlags2 & 0x02)
            //{
            //    char BattleStationSide;
            //}

            // Are we a pet?
            //if (packetFlags2 & 0x04)
            //{
            //    long PetMaster;
            //}

            _writer.PushByte(0);

            Byte[] reply = _writer.Finish();

            // Set Packet Flags
            Byte[] m_packetFlags;
            m_packetFlags = BitConverter.GetBytes(packetFlags);
            Array.Reverse(m_packetFlags);
            reply[30] = m_packetFlags[0]; reply[31] = m_packetFlags[1];
            reply[32] = m_packetFlags[2]; reply[33] = m_packetFlags[3];

            return reply;
        }
    }
}
